package com.xyd.Servlet;

import com.xyd.Biz.Impl.ManagerLoginBizImpl;
import com.xyd.Biz.ManagerLoginBiz;
import com.xyd.Entity.ManageUser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/ManagerLoginServlet")
public class ManagerLoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String name = request.getParameter("userName");
        String pwd = request.getParameter("passWord");

        HttpSession session = request.getSession();
        String CheckCode_session = String.valueOf(session.getAttribute("CHECKCODE_SERVER"));

        //获取到用户输入的验证码
        String code = request.getParameter("veryCode");

        //将用户输入的验证码与session中取出的验证码进行比较，相等的话就进行登录操作不成功则返回得到登录界面
        if (session.getAttribute("checkCode").toString().equalsIgnoreCase(code)) {
            ManageUser manageUser = new ManageUser();
            manageUser.setUsername(name);
            manageUser.setPwd(pwd);

            ManagerLoginBiz managerLoginBiz = new ManagerLoginBizImpl();

            ManageUser manage = managerLoginBiz.ManagerLogin(manageUser);

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time = df.format(new Date());// new Date()为获取当前系统时间

        if (manage != null){
            request.getSession().setAttribute("manageUser",manage);
            request.getSession().setAttribute("time",time);
            response.sendRedirect("html/manage/index.jsp");

                request.setAttribute("login", "登录成功！");


            } else {
                response.getWriter().write("<script>alert('用户名或密码错误！');history.go(-1);</script>");
            }
        } else {
            response.getWriter().write("<script>alert('验证码输入错误！');history.go(-1);</script>");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}


